<template>
  <div class="order-management">
    <h1>订单管理</h1>
    
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable style="width: 150px;">
            <el-option label="全部" value="" />
            <el-option label="已完成" value="completed" />
            <el-option label="准备中" value="preparing" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="配送中" value="delivering" />
            <el-option label="待处理" value="pending" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <el-table 
        v-loading="loading"
        :data="pagedOrders" 
        border 
        style="width: 100%"
      >
        <el-table-column prop="orderNumber" label="订单编号" width="120" />
        <el-table-column prop="contactName" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="130" />
        <el-table-column prop="deliveryLocation" label="配送地址" min-width="180" show-overflow-tooltip />
        <el-table-column label="配送时间窗口" width="220">
          <template #default="{row}">
            {{ formatTimeWindow(row.deliveryTimeWindow) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额(元)" width="120" align="right">
          <template #default="{row}">
            {{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{row}">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template #default="{row}">
            {{ getPaymentMethodText(row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentStatus" label="支付状态" width="120">
          <template #default="{row}">
            <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
              {{ getPaymentStatusText(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{row}">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="filteredOrders.length"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const orders = ref([])

// 筛选表单
const filterForm = ref({
  status: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 状态映射
const statusMap = {
  completed: '已完成',
  preparing: '准备中',
  cancelled: '已取消',
  delivering: '配送中',
  pending: '待处理'
}

// 支付方式映射
const paymentMethodMap = {
  mobile_payment: '移动支付',
  credit_card: '信用卡',
  cash: '现金'
}

// 支付状态映射
const paymentStatusMap = {
  paid: '已支付',
  pending: '待支付',
  failed: '支付失败',
  refunded: '已退款'
}

// 获取订单数据
const fetchOrders = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }

    const response = await axios.post('http://localhost:8081/orders/list', params, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 200) {
      orders.value = response.data.data.list
    } else {
      ElMessage.error(response.data.message || '获取订单数据失败')
    }
  } catch (error) {
    ElMessage.error('请求出错: ' + error.message)
    console.error('API请求错误:', error)
  } finally {
    loading.value = false
  }
}

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status] || status
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  return paymentMethodMap[method] || method
}

// 获取支付状态文本
const getPaymentStatusText = (status) => {
  return paymentStatusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    completed: 'success',
    preparing: '',
    cancelled: 'danger',
    delivering: 'warning',
    pending: 'info'
  }
  return types[status] || ''
}

// 获取支付状态标签类型
const getPaymentStatusTagType = (status) => {
  const types = {
    paid: 'success',
    pending: 'warning',
    failed: 'danger',
    refunded: 'info'
  }
  return types[status] || ''
}

// 格式化时间窗口
const formatTimeWindow = (timeWindow) => {
  if (!timeWindow) return ''
  return timeWindow.replace(' ', ' ').replace('-', ' ~ ')
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-')
}

// 筛选订单
const filteredOrders = computed(() => {
  let result = [...orders.value]
  
  // 状态筛选
  if (filterForm.value.status) {
    result = result.filter(order => order.status === filterForm.value.status)
  }
  
  return result
})

// 分页数据
const pagedOrders = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredOrders.value.slice(start, end)
})

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchOrders()
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    status: ''
  }
  currentPage.value = 1
  fetchOrders()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchOrders()
}

// 当前页变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchOrders()
}

// 初始化获取数据
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
}

.el-table {
  margin-top: 10px;
}

.el-form-item {
  margin-right: 20px;
  margin-bottom: 0;
}
</style>